package com.foreveross.bsl;

import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import com.foreveross.bsl.manager.CubeModuleManager;
import com.foreveross.bsl.manager.ModuleOperationService;
import com.foreveross.bsl.manager.ModuleOperationService.ModuleOperationServiceBinder;
import com.foreveross.bsl.model.CubeApplication;
import com.foreveross.bsl.model.UserPrivilege;
import com.foreveross.chameleon.AppStatus;
import com.foreveross.chameleon.manager.R;
import com.foreveross.chameleonsdk.CModule;
import com.foreveross.data.DataProvider;
import com.foreveross.push.nodeclient.NotificationPacketListener;
import com.foreveross.push.tmp.OriginalParser;
import com.foss.AppLog;

public class CmanagerModule extends CModule {

    private static CmanagerModule cmanagerModule;
    public static SharedPreferences sharePref;
    private Context context;
    CubeApplication cubeApplication;
    ModuleOperationService moduleOperationService = null;

    @Override
    public void onCreate(CModule cModule) {
        AppLog.printProcess("oncreate");
        super.onCreate(cModule);
        AppStatus.USERLOGIN = false;
        AppStatus.FROMLOGIN = false;
        cmanagerModule = (CmanagerModule) cModule;
        init();
        readConfig(R.raw.pushmodule);
        UserPrivilege.getInstance();
    }

    public static CmanagerModule getCmanagetModule() {
        return cmanagerModule;
    }

    private void init() {
        context = getcApplication().getmContext();
        sharePref = PreferenceManager.getDefaultSharedPreferences(context);
        cubeApplication = CubeApplication.getInstance(getcApplication().getmContext());
        cubeApplication.loadApplication();
        NotificationPacketListener.register(new OriginalParser(context));
        CubeModuleManager.getInstance().init(cubeApplication);
        DataProvider.getInstance(context, "cube");
        context.bindService(ModuleOperationService.getIntent(context), moduleServiceConnection,
                Context.BIND_AUTO_CREATE);
    }


    private ServiceConnection moduleServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            moduleOperationService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            moduleOperationService = ((ModuleOperationServiceBinder) service).getService();
            CubeModuleManager.getInstance().setModuleOperationService(moduleOperationService);
        }
    };


    public String getActivity() {
        return "com.foreveross.bsl.CAdminActivity";
    }


    @Override
    public void onExit(CModule cModule) {
        super.onExit(cModule);
        CubeModuleManager.getInstance().stopTask();
    }
}
